﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;
using XbdSoft.Client;
using XbdSoft.Contract;
using XbdSoft.Domain;
using XbdSoft.Controls;
using System.Threading;

namespace XbdSoft
{
    public partial class XbdMP3RecDownload : DockContent
    {
        public XbdMP3RecDownload()
        {
            InitializeComponent();
        }

        private void XbdMP3RecDownload_Load(object sender, EventArgs e)
        {
            DownloadListDataGridView.AutoGenerateColumns = false;
            BindRecommendTreeView();
            BindDownloadInfoTreeView();
            //BindDownloadImageList();
        }

        private void BindRecommendTreeView()
        {
            var rootNode = RecommendTreeView.Nodes[0];
            rootNode.Tag = "";
            rootNode.Nodes.Clear();

            using (var downloadService = new ServiceObject<IDownloadService>(Util.DownloadServiceAddress))
            {
                var allRecommends = downloadService.Object.GetRecommendDownloadCategories();
                foreach (var recommend in allRecommends)
                {
                    var node = new TreeNode();
                    node.Tag = recommend;
                    node.Name = recommend.Name;
                    node.Text = recommend.Name;
                    rootNode.Nodes.Add(node);
                }
            }
            RecommendTreeView.ExpandAll();
            if (RecommendTreeView.Nodes[0].Nodes.Count > 0)
            {
                RecommendTreeView.SelectedNode = RecommendTreeView.Nodes[0].Nodes[0];
            }
            else
            {
                RecommendTreeView.SelectedNode = RecommendTreeView.Nodes[0];
            }
        }

        private void BindDownloadInfoTreeView()
        {
            DownloadInfoTreeView.ExpandAll();
        }

        private void BindDownloadImageList()
        {
            var recommends = new List<AudioCategory>();

            var selectedRecommendNode = RecommendTreeView.SelectedNode;
            if (selectedRecommendNode != null && selectedRecommendNode.Tag != null)
            {
                // Is Root Node, select all recommends
                if (selectedRecommendNode.Tag.ToString() == string.Empty)
                {
                    foreach (TreeNode childNode in selectedRecommendNode.Nodes)
                    {
                        var childRecommend = childNode.Tag as AudioCategory;
                        if (childRecommend != null)
                        {
                            recommends.Add(childRecommend);
                        }
                    }
                }
                else
                {
                    var recommend = selectedRecommendNode.Tag as AudioCategory;
                    if (recommend != null)
                    {
                        recommends.Add(recommend);
                    }
                }
            }

            var allResourcecs = new List<DownloadDTO>();
            using (var service = new ServiceObject<IDownloadService>(Util.DownloadServiceAddress))
            {
                foreach (var category in recommends)
                {
                    foreach (var resource in category.AudioResources)
                    {
                        var downloadUrl = service.Object.GetDownloadUrl(resource.ID);
                        var downloadObject = new WebClientDownload(downloadUrl);
                         
                        allResourcecs.Add(new DownloadDTO
                        { 
                            ID = resource.ID,
                            Description = resource.Title,
                            Type = resource.Type,
                            Category = category.Name,
                            Download = "下载",
                            TryListen = "试听",
                            DownloadUrl = downloadUrl,
                            DownloadObject = downloadObject,
                            Size = "",
                            Status = "等待下载",
                            Speed = "0kb/s",
                            Progress = 0
                        }); 
                    }
                }
            }
            DownloadListDataGridView.DataSource = allResourcecs;
            UpdateDataGridViewStatus();
            //this.BeginInvoke(new Action(()=>UpdateDataGridViewStatus()));
        }
         

        private void RecommendTreeView_AfterSelect(object sender, TreeViewEventArgs e)
        {
            BindDownloadImageList();
        }

        private void DownloadInfoTreeView_AfterSelect(object sender, TreeViewEventArgs e)
        {
            BindDownloadImageList();
        }
         
        private void DownloadListDataGridView_SelectionChanged(object sender, EventArgs e)
        {
            DownloadDescriptionLabel.Text = "";
            DownloadSavePathLabel.Text = "";
            if (DownloadListDataGridView.SelectedRows.Count > 0)
            {
                var row = DownloadListDataGridView.SelectedRows[0];
                dynamic data = row.DataBoundItem;

                DownloadDescriptionLabel.Text = data.Description;
                DownloadSavePathLabel.Text = @"C:\Users";
            }
        }

        private void DownloadListDataGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
        }

        private void DownloadListDataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            var column = DownloadListDataGridView.Columns[e.ColumnIndex];
            if (column == DownloadColumn)
            {
                DownloadDTO cell = DownloadListDataGridView.Rows[e.RowIndex].DataBoundItem as DownloadDTO;
                WebClientDownload download = cell.DownloadObject as WebClientDownload;
                download.SaveFilePath = @"D:\ddd.mp3"; 
                Action action = download.Download;
                action.BeginInvoke(new AsyncCallback(result => { 
                }), null);
            }
            else if (column == TryListenColumn)
            {
                MessageBox.Show("试听");
            }
        }

        void download_DownloadChanged(object sender, DownloadChangedEventArgs e)
        {
            //throw new NotImplementedException();
        }

        Dictionary<int, DownloadDTO> downloadDTOs = new Dictionary<int, DownloadDTO>();
        void UpdateDataGridViewStatus()
        {
            downloadDTOs.Clear();
            foreach (DataGridViewRow row in DownloadListDataGridView.Rows)
            {
                dynamic bindItem = row.DataBoundItem;
                if (bindItem != null &&   bindItem  is DownloadDTO)
                {
                    var dto = bindItem as DownloadDTO;
                    dto.DownloadObject.DownloadChanged += new EventHandler<DownloadChangedEventArgs>(DownloadObject_DownloadChanged);
                    downloadDTOs.Add(row.Index, dto);
                }
            }
        }


        void DownloadObject_DownloadChanged(object sender, DownloadChangedEventArgs e)
        {
            var keyValuePair = downloadDTOs.FirstOrDefault(kv => kv.Value.DownloadObject == sender as WebClientDownload);
            if (keyValuePair.Value != null)
            {
                var row = DownloadListDataGridView.Rows[keyValuePair.Key];
                var download = keyValuePair.Value.DownloadObject;
                row.Cells[SizeColumn.Index].Value = string.Format("{0:N2}MB/{1:N2}MB", (download.TotalLength * 1.0 / (1024 * 1024)), (download.DownloadLength * 1.0 / (1024 * 1024)));
                row.Cells[ProgressColumn.Index].Value = Math.Round((float)(download.DownloadLength * 100.0 / download.TotalLength), 2);
                row.Cells[StatusColumn.Index].Value = download.Status;
                row.Cells[SpeedColumn.Index].Value = string.Format("{0:N2}kb/s",download.Speed);
            }
            //throw new NotImplementedException();
        }
    }

    public class DownloadDTO
    {
        public long ID { get; set; }
        public string Description { get; set; }
        public string Type { get; set; }
        public string Category { get; set; }
        public string Download { get; set; }
        public string TryListen { get; set; }
        public string DownloadUrl { get; set; }
        public IDownload DownloadObject { get; set; }
        public string Size { get; set; }
        public string Status { get; set; }
        public string Speed { get; set; }
        public float Progress { get; set; }
    }
}
